// app/controller/product_category_controller.js
'use strict';

const Controller = require('egg').Controller;
const Joi = require('joi');

class ProductCategoryController extends Controller {
  // 获取所有启用的类目树形结构
  async getCategoryTree() {
    const { ctx } = this;
    
    try {
      const categories = await ctx.model.ProductCategoryModel.findAll({
        where: {
          status: 'active'
        },
        order: [['sort', 'ASC'], ['id', 'ASC']]
      });
      
      // 构建树形结构
      const tree = this.buildCategoryTree(categories);
      
      ctx.success(tree);
    } catch (error) {
      ctx.logger.error('获取产品类目树失败:', error);
      ctx.error(`获取产品类目树失败: ${error.message}`);
    }
  }
  
  // 构建类目树形结构
  buildCategoryTree(categories) {
    // 将categories转换为map以便快速查找
    const categoryMap = {};
    categories.forEach(category => {
      categoryMap[category.id] = {
        ...category.toJSON(),
        children: []
      };
    });
    
    // 构建树形结构
    const tree = [];
    categories.forEach(category => {
      if (category.parentId === null) {
        tree.push(categoryMap[category.id]);
      } else if (categoryMap[category.parentId]) {
        categoryMap[category.parentId].children.push(categoryMap[category.id]);
      }
    });
    
    return tree;
  }
  
  // 获取所有启用的类目列表（扁平结构）
  async getCategoryList() {
    const { ctx } = this;
    
    try {
      const categories = await ctx.model.ProductCategoryModel.findAll({
        where: {
          status: 'active'
        },
        order: [['level', 'ASC'], ['sort', 'ASC'], ['id', 'ASC']]
      });
      
      ctx.success(categories);
    } catch (error) {
      ctx.logger.error('获取产品类目列表失败:', error);
      ctx.error(`获取产品类目列表失败: ${error.message}`);
    }
  }
}

module.exports = ProductCategoryController;